﻿<%@ WebHandler Language="C#" Class="_login" %>

using System;
using System.Web;
using System.Data;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using WechatUtility;
using NS.Utilities;
using NS.BLL.Systems;
using BLL;
using Model;

public class _login : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        //取得处事类型
        string action = context.Request["ac"];

        switch (action)
        {
            case "sms": //发送验证码
                sendSms(context);
                break;
            case "reg": //注册用户
                register(context);
                break;
            case "active": //员工激活
                active(context);
                break;
            case "isactive": //员工是否激活
                isactive(context);
                break;
        }
    }

    private void sendSms(HttpContext context)
    {
        string result = string.Empty;
        string mobile = context.Request["mobile"];
        string code = (new Random().Next(9999)).ToString().PadLeft(4, '0');
        if (MemberService.IsExistMobile(mobile))
        {
            result = JsonMessager.Fail("手机号已注册");
        }
        else
        {
            SmsCode Model = new SmsCode();
            Model.Mobile = mobile;
            Model.Code = code;
            Model.SendTime = DateTime.Now;
            if (SmsCodeService.AddSmsCode(Model) > 0)
            {
                // 设置为您的apikey(https://www.yunpian.com)可查
                string apikey = WebConfigHelper.GetAppSet("SMSKey");
                // 发送内容
                string text = "【爱尚洗车】您的验证码是" + code + "。如非本人操作，请忽略本短信。祝您洗车愉快。";
                // 智能模板发送短信url
                string url_send_sms = "https://sms.yunpian.com/v1/sms/send.json";
                string data_send_sms = "apikey=" + apikey + "&mobile=" + mobile + "&text=" + text;
                string res = "[" + HttpPost(url_send_sms, data_send_sms) + "]";

                object[] rc = JsonHelper.JSON2T<object[]>(res);
                Dictionary<String, object> rcDic = (Dictionary<String, object>)rc[0];
                if (rcDic["code"].ToString() == "0")
                {
                    result = JsonMessager.Success("发送成功");
                }
                else
                {
                    WxPay.Log.Error(this.GetType().ToString(), "验证码发送失败。code：" + rcDic["code"].ToString());
                    result = JsonMessager.Fail("发送失败");
                }
            }
            else
            {
                result = JsonMessager.Fail("发送失败");
            }
        }
        context.Response.Write(result);
    }

    public static string HttpPost(string Url, string postDataStr)
    {
        String res = String.Empty;
        byte[] dataArray = Encoding.UTF8.GetBytes(postDataStr);

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = dataArray.Length;
        Stream dataStream = request.GetRequestStream();
        dataStream.Write(dataArray, 0, dataArray.Length);
        dataStream.Close();
        try
        {
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            res = reader.ReadToEnd();
            reader.Close();
        }
        catch (Exception e)
        {
            res = "{\"code\":99,\"msg\":\"" + e.Message + "\",\"detail\":\"" + e.ToString() + "\"}";
        }

        return res;
    }

    public class ReturnCode
    {
        public string code { get; set; }
        public double msg { get; set; }
        public double detail { get; set; }
    }


    private void register(HttpContext context)
    {
        string result = string.Empty;
        string mobile = context.Request["mobile"];
        string code = context.Request["code"];
        string openid = context.Request["openid"];
        string referrer = context.Request["referrer"];

        if (WebConfigHelper.GetAppSet("Debug") == "0" && !SmsCodeService.Validate(mobile, code))
        {
            result = "验证码错误";
        }
        else if (MemberService.IsExistMobile(mobile))
        {
            result = "手机号已注册";
        }
        else if (!string.IsNullOrEmpty(referrer) && referrer.Substring(0, 1).ToUpper() == "S")
        {
            if (PartnerService.GetNum(referrer) <= 0)
            {
                result = "未找到合作商家";
            }
        }

        if (string.IsNullOrEmpty(result))
        {
            bool res = false;
            Member Model = MemberService.GetMemberByOpenID(openid);
            if (Model == null)
            {
                Model = new Member();
                Model.Mobile = mobile;
                Model.OpenID = openid;
                Model.IsLock = 0;
                ArrayList sqlList = new ArrayList();
                sqlList.Add(MemberService.AddMember_SQL(Model));

                if (!string.IsNullOrEmpty(referrer))
                {
                    //商家推荐
                    if (referrer.Substring(0, 1).ToUpper() == "S")
                    {
                        MemberRelation mr = new MemberRelation();
                        mr.MemberID = openid;
                        mr.PartnerID = referrer;
                        mr.RelationDate = DateTime.Now;

                        sqlList.Add(MemberRelationService.AddMemberRelation_SQL(mr));
                    }
                    else
                    {
                        string refid = MemberService.GetOpenIDbyMobile(referrer);
                        if (!string.IsNullOrEmpty(refid))
                        {
                            MemberRelation mr = new MemberRelation();
                            mr.MemberID = openid;
                            mr.PartnerID = refid;
                            string[] family = MemberRelationService.GetFamily(refid);
                            mr.PartnerID2 = family[0];
                            mr.PartnerID3 = family[1];
                            mr.RelationDate = DateTime.Now;

                            sqlList.Add(MemberRelationService.AddMemberRelation_SQL(mr));
                        }
                    }
                }
                //没有购买过优惠券
                if (CouponsService.IsFirst(openid))
                {
                    //商家体验券
                    if (!string.IsNullOrEmpty(referrer) && referrer.Substring(0, 1).ToUpper() == "S")
                    {
                        for (int i = 0; i < PartnerService.GetNum(referrer); i++)
                        {
                            Coupons cm = new Coupons();
                            cm.OpenID = openid;
                            cm.Money = 0;
                            cm.Explain = "免费体验券";
                            cm.YouXQStart = DateTime.Now;
                            cm.YouXQEnd = DateTime.Now.AddMonths(1);
                            cm.CouType = 1;
                            sqlList.Add(CouponsService.AddCoupons_SQL(cm));
                        }
                    }
                    else
                    {
                        //首单优惠券
                        Coupons cm = new Coupons();
                        cm.OpenID = openid;
                        cm.Money = decimal.Parse(DictionaryService.GetDicValue("首单优惠", "金额"));
                        cm.Explain = "首单立减" + cm.Money + ".00元";
                        cm.YouXQStart = DateTime.Now;
                        cm.YouXQEnd = DateTime.Now.AddYears(1);
                        cm.CouType = 0;
                        sqlList.Add(CouponsService.AddCoupons_SQL(cm));
                    }
                }
                res = OrderService.TransUpdate(sqlList);
            }
            else
            {
                Model.Mobile = mobile;
                res = MemberService.UpdateMemberByMemberID(Model) > 0;
            }
            if (!res)
            {
                result = "用户注册失败";
            }
        }

        if (string.IsNullOrEmpty(result))
        {
            result = JsonMessager.Success("用户注册成功");
        }
        else
        {
            result = JsonMessager.Fail(result);
        }
        context.Response.Write(result);
    }

    private void active(HttpContext context)
    {
        string mobile = context.Request["mobile"];
        string openid = context.Request["openid"];
        string result = UserService.Activate(mobile, openid);
        if (string.IsNullOrEmpty(result))
        {
            result = JsonMessager.Success("登录成功");
        }
        else
        {
            result = JsonMessager.Fail(result);
        }

        context.Response.Write(result);
    }
    private void isactive(HttpContext context)
    {
        string result = string.Empty;
        if (!string.IsNullOrEmpty(CookieHelper.GetValue("openid")))
        {
            string openid = CookieHelper.GetValue("openid");
            if (!UserService.IsActivate(openid))
            {
                result = "未激活";
            }
        }
        else
        {
            result = "未找到Openid";
        }
        if (string.IsNullOrEmpty(result))
        {
            result = JsonMessager.Success("登录成功");
        }
        else
        {
            result = JsonMessager.Fail(result);
        }
        context.Response.Write(result);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}